<template>
  <div class="container">
    <!-- 顶部欢迎区域 -->
    <div class="home_header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>首页</el-breadcrumb-item>
      </el-breadcrumb>
      <el-space :size="20">
        <div class="big_image">
          <el-image style="width: 60px; height: 60px" :src="adminImageUrl || imageUrl" fit="fit" />
        </div>
        <div class="welcome">
          <span>{{ greeting }}</span><br>
          <span>Hi～～～欢迎来到Fright For Dream开发的享悦音乐</span>
        </div>
      </el-space>
    </div>

    <!-- 数据统计卡片 -->
    <el-row class="cards" justify="space-evenly">
      <el-col :span="6">
        <el-card style="height: 80px">
          <div>用户数量<br /><span>{{ userCount }}</span></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card style="height: 80px">
          <div>歌手数量<br /><span>{{ singerCount }}</span></div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card style="height: 80px">
          <div>歌曲数量<br /><span>{{ musicCount }}</span></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 日志区域 -->
    <div class="log">
      <h4>日志</h4>
      <el-table 
        :data="tableData" 
        v-loading="loading"
        element-loading-text="加载中..."
        style="width: 100%">
        <el-table-column prop="userName" label="用户" width="180" />
        <el-table-column prop="doSome" label="操作" width="180" />
        <el-table-column prop="createDate" label="时间" />
      </el-table>

      <div class="page">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script>
import imageUrl from '@/assets/default.png'

export default {
  name: "Home",
  data() {
    return {
      imageUrl,
      userCount: 0,
      singerCount: 0,
      musicCount: 0,
      adminImageUrl: '',
      tableData: [],
      greeting: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      loading: false,
    };
  },
  created() {
    const hour = new Date().getHours();
    if (hour < 12) {
      this.greeting = '早上好';
    } else if (hour < 18) {
      this.greeting = '下午好';
    } else {
      this.greeting = '晚上好';
    }

    this.fetchHomeData();
    this.fetchLogData();
  },
  methods: {
    async fetchHomeData() {
      try {
        const res = await fetch('/api/home/statistics');
        const result = await res.json();
        if (result.code === 20000 && result.data) {
          this.userCount = result.data.userCount;
          this.singerCount = result.data.singerCount;
          this.musicCount = result.data.musicCount;
          this.adminImageUrl = result.data.adminImageUrl || imageUrl;
        } else {
          this.resetHomeCounts();
        }
      } catch (e) {
        this.resetHomeCounts();
      }
    },

    resetHomeCounts() {
      this.userCount = 0;
      this.singerCount = 0;
      this.musicCount = 0;
      this.adminImageUrl = imageUrl;
    },

    async fetchLogData() {
      this.loading = true;
      try {
        const response = await fetch('/api/logInfo/page', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            pageIndex: this.currentPage,
            pageSize: this.pageSize
          })
        });

        const result = await response.json();
        if (result.code === 20000 && result.data) {
          const { list = [], total = 0 } = result.data;
          this.tableData = list.map(item => ({
            ...item,
            createDate: this.formatDate(item.createDate)
          }));
          this.total = total;
        } else {
          this.tableData = [];
          this.total = 0;
          console.error('日志接口返回错误:', result);
        }
      } catch (e) {
        console.error('日志获取失败:', e);
        this.tableData = [];
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },

    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchLogData();
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchLogData();
    }
  }
}
</script>

<style scoped lang="less">
.container {
  margin-top: -20px;
  margin-left: -20px;
  padding: 0;
}
.home_header {
  box-shadow: 6px 6px 6px #ced4da;
  background-color: #fff;
  padding: 10px;
  height: 90px;
}
.big_image {
  margin: 20px 0px 0px 10px;
}
.welcome {
  font-size: 16px;
  color: #999;
}
.cards {
  background-color: white;
  margin-top: 10px;
  box-shadow: 6px 6px 6px #ced4da;
  div {
    text-align: center;
    span {
      color: blue;
    }
  }
}
.log {
  margin-top: 10px;
  margin-left: 10px;
  padding: 10px;
  background-color: white;
  box-shadow: 6px 6px 6px #ced4da;
}
.page {
  width: 50%;
  margin: 10px auto 0;
}
</style>
